/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.kylin.common.core.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Http与Servlet工具类.
 * @author ThinkGem
 * @version 2014-8-19
 */
public class ServletUtils {

	private ServletUtils() {
		throw new IllegalStateException("Utility class");
	}

	/**
	 * 获取String参数
	 */
	public static String getParameter(String name)
	{
		HttpServletRequest request = getRequest();
		if(Objects.isNull(request)) {
			return null;
		}
		return request.getParameter(name);
	}

	/**
	 * 获取String参数
	 */
	public static String getParameter(String name, String defaultValue)
	{
		String value = getParameter(name);
		if(StringUtils.isNotBlank(value)) {
			return value;
		}
		return defaultValue;
	}

	/**
	 * 获取Integer参数
	 */
	public static Integer getParameterToInt(String name)
	{
		try {
			HttpServletRequest request = getRequest();
			if(!Objects.isNull(request)) {
				String value = request.getParameter(name);
				if(StringUtils.isNotBlank(value)) {
					return Integer.parseInt(value);
				}
				return null;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取Integer参数
	 */
	public static Integer getParameterToInt(String name, Integer defaultValue)
	{
		Integer value = getParameterToInt(name);
		if(Objects.isNull(value)) {
			return defaultValue;
		}
		return value;
	}

	/**
	 * 从请求体中获取请求数据
	 */
	public static String getRequestBody(HttpServletRequest request) throws IOException {
//		StringBuilder sb = new StringBuilder();
//		BufferedReader reader = request.getReader();
//		String line;
//		while ((line = reader.readLine()) != null) {
//			sb.append(line);
//		}
//		return sb.toString();

		// 从请求体中获取JSON字符串
		String requestBody;
		try (BufferedReader reader = request.getReader()) {
			requestBody = reader.lines().collect(Collectors.joining(System.lineSeparator()));
		}
		return  requestBody;
	}

	
	/**
	 * 获取当前请求对象
	 * web.xml: <listener><listener-class>
	 * 	org.springframework.web.context.request.RequestContextListener
	 * 	</listener-class></listener>
	 */
	public static HttpServletRequest getRequest(){
		try{
			ServletRequestAttributes requestAttributes  = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
			return requestAttributes.getRequest();
		}catch(Exception e){
			return null;
		}
	}
	
	/**
	 * 获取当前相应对象
	 * web.xml: <filter><filter-name>requestContextFilter</filter-name><filter-class>
	 * 	org.springframework.web.filter.RequestContextFilter</filter-class></filter><filter-mapping>
	 * 	<filter-name>requestContextFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
	 */
	public static HttpServletResponse getResponse(){
		HttpServletResponse response = null;
		try{
			response = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getResponse();
			if (response == null){
				return null;
			}
		}catch(Exception e){
			return null;
		}
		return response;
	}

	public static HttpServletRequest getHttpServletRequest() {

		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if(Objects.isNull(requestAttributes)) {
			return null;
		}
		return requestAttributes.getRequest();
	}

	/**
	 * 获取当前网络ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request){
		String ipAddress = request.getHeader("x-forwarded-for");
		if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
				//根据网卡取本机配置的IP
				InetAddress inet=null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress= inet.getHostAddress();
			}
		}
		//对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
			if(ipAddress.indexOf(",")>0){
				ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
}
